package com.cetcs.kmga.hbase.index;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Hbase数据库连接池
 *
 * @author xutao
 * @version V1.0 创建时间：2017-08-30 11:27
 *          Copyright 2017 by CETC
 */
public class DruidPool {

    private static DruidPool druidPool;

    private static DruidDataSource hbaseSource;

    private final static String HBASE_PATH = "druid-hbase.properties";

    private final static Properties hbaseProperties = new Properties();

    private final static Logger LOGGER = LoggerFactory.getLogger(DruidPool.class);

    static {
        try {
            LOGGER.info("load hbase properties");
            hbaseProperties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(HBASE_PATH));
            hbaseSource = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(hbaseProperties);
            druidPool = new DruidPool();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获取hbase初始化连接池" + e.getMessage());
        }
    }

    private DruidPool() {
    }

    public static DruidPool getInstance() {
        return druidPool;
    }


    public Connection getConnection() {
        try {
            if (hbaseSource != null) {
                return hbaseSource.getConnection();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error("获取连接失败" + e.getMessage(), e);
        }
        return null;
    }

    public static void close(Connection con) {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            LOGGER.error("关闭连接" + e.getMessage());
        }
        return;
    }

}
